<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFromRef" :model="queryParams" inline label-width="100px">
        <el-form-item label="beanName">
          <el-input v-model="queryParams.beanName" placeholder="" />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="状态">
            <el-option label="正常" value="0" />
            <el-option label="停止" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
          <el-button v-hasPerm="['sys:job:add']" type="success" @click.stop="handleOpenDialog()">
            <i-ep-plus />
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card class="table-container" shadow="never">
      <el-table v-loading="loading" :data="list" stripe style="width: 100%">
        <el-table-column label="ID" min-width="50" prop="id" width="50" />
        <el-table-column label="beanName" prop="beanName" width="250" />
        <el-table-column label="配置状态" prop="status" width="200">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" size="small" type="success">正常</el-tag>
            <el-tag v-else-if="scope.row.status === 1" size="small" type="danger">暂停</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="下次执行时间" prop="nextFireTime" width="250" />

        <el-table-column label="启动参数" prop="params" width="100" />
        <el-table-column label="cron表达式" prop="cronExpression" width="150" />
        <el-table-column label="备注" prop="remark" width="300" />

        <el-table-column fixed="right" label="操作" width="300">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:jobLog:query']"
              link
              size="small"
              type="primary"
              @click.stop="handleJobLogQuery(scope.row.id)"
            >
              历史记录
            </el-button>
            <el-button
              v-hasPerm="['sys:job:doAction']"
              link
              size="small"
              type="danger"
              @click.stop="handleAction(scope.row.id, 'run')"
            >
              启动
            </el-button>
            <el-button
              v-hasPerm="['sys:job:doAction']"
              link
              size="small"
              type="danger"
              @click.stop="handleAction(scope.row.id, 'pause')"
            >
              暂停
            </el-button>

            <el-button
              v-hasPerm="['sys:post:delete']"
              link
              size="small"
              type="primary"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              修改
            </el-button>

            <el-button
              v-hasPerm="['sys:job:delete']"
              link
              size="small"
              type="danger"
              @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        v-model:total="total"
        @pagination="handleQuery"
      />
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" size="50%" @close="handleCloseDialog">
      <el-form ref="addFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="beanName" prop="beanName">
          <el-input v-model="formData.beanName" placeholder="" />
        </el-form-item>

        <el-form-item label="启动参数" prop="params">
          <el-input v-model="formData.params" placeholder="" />
        </el-form-item>

        <el-form-item label="cron表达式" prop="cronExpression">
          <el-input v-model="formData.cronExpression" placeholder="" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" placeholder="" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-drawer
      v-model="dialogFlagJobLog"
      size="90%"
      title="任务运行记录"
      @close="handleCloseDialogJobLog"
    >
      <el-card class="table-container" shadow="never">
        <template #header>
          <el-button v-hasPerm="['sys:jobLog:query']" type="success" @click="handleJobLogQuery2()">
            <i-ep-search />
            刷新
          </el-button>
          <el-button
            v-hasPerm="['sys:jobLog:deleteAll']"
            type="danger"
            @click="handleDeleteJobLogAll()"
          >
            <i-ep-delete />
            全部删除
          </el-button>
        </template>

        <el-table v-loading="loadingJobLog" :data="listJobLog" stripe style="width: 100%">
          <el-table-column label="ID" min-width="50" prop="id" width="80" />
          <el-table-column label="beanName" prop="beanName" width="200" />
          <el-table-column label="运行时间" prop="createTime" width="200" />
          <el-table-column label="耗时" prop="cost" width="100" />

          <el-table-column label="启动参数" prop="params" width="200" />
          <el-table-column label="错误码" prop="errorCode" width="100" />
          <el-table-column label="错误信息" prop="errorMsg" width="200" />
          <el-table-column label="备注" prop="remark" width="200" />

          <el-table-column fixed="right" label="操作" width="80">
            <template #default="scope">
              <el-button
                v-hasPerm="['sys:jobLog:delete']"
                link
                size="small"
                type="danger"
                @click.stop="handleDeleteJobLog(scope.row.jobId, scope.row.id)"
              >
                <i-ep-delete />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total > 0"
          v-model:limit="queryParamsJobLog.pageSize"
          v-model:page="queryParamsJobLog.pageNum"
          v-model:total="totalJobLog"
          @pagination="handleQueryJobLog"
        />
      </el-card>
    </el-drawer>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Job',
  inheritAttrs: false
})

import { ElForm, ElTable } from 'element-plus'
import { onMounted, ref } from 'vue'
import request from '@/utils/request'

const BASE_URL = '/api/yyplatform/admin/schedule/job/'

// ====================================================================================================
const list = ref([])
const total = ref(0)
const loading = ref(false)

const queryFromRef = ref()

const queryParams = ref({
  beanName: '',
  status: '0',
  pageNum: 1,
  pageSize: 20
})

// ====================================================================================================

const addFormRef = ref(ElForm)
const formData = ref({
  id: '',
  beanName: '',
  cronExpression: '',
  params: '',
  remark: ''
})
const dialog = ref({
  title: '',
  visible: false
})
const rules = ref({
  beanName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  cronExpression: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

// ====================================================================================================

const listJobLog = ref([])
const totalJobLog = ref(0)
const loadingJobLog = ref(false)
const dialogFlagJobLog = ref(false)
const currentJobId = ref(0)

const queryParamsJobLog = ref({
  pageNum: 1,
  pageSize: 10
})

async function handleJobLogQuery2() {
  queryParamsJobLog.value = {
    pageNum: 1,
    pageSize: 10
  }
  await handleJobLogQuery(currentJobId.value)
}

async function handleJobLogQuery(id) {
  currentJobId.value = id
  queryParamsJobLog.value = {
    pageNum: 1,
    pageSize: 10
  }

  console.log(queryParamsJobLog, 'queryParamsJobLog')

  loadingJobLog.value = true
  request({
    url: `${BASE_URL}/log/query`,
    method: 'get',
    params: {
      jobId: id,
      ...queryParamsJobLog.value
    }
  }).then((res) => {
    console.log(res, 'res')
    dialogFlagJobLog.value = true
    loadingJobLog.value = false
    listJobLog.value = res.content
    totalJobLog.value = parseInt(res.totalElements)
  })
}

function handleCloseDialogJobLog() {
  dialogFlagJobLog.value = false
}

function handleDeleteJobLog(jobId, logId) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/log/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: logId
      }
    }).then(() => {
      handleJobLogQuery(jobId)
    })
  })
}

function handleDeleteJobLogAll() {
  const jobId = currentJobId.value

  request({
    url: `${BASE_URL}/log/deleteAll`,
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: {
      jobId: jobId
    }
  }).then(() => {
    handleJobLogQuery(jobId)
  })
}

// ====================================================================================================

async function handleOpenDialog(id) {
  if (id) {
    let res = await request({
      url: `${BASE_URL}/get?id=${id}`,
      method: 'get'
    })
    formData.value = res
    dialog.value.visible = true
    dialog.value.title = '修改定时任务'
  } else {
    dialog.value.visible = true
    dialog.value.title = '添加定时任务'
    formData.value = {
      id: '',
      beanName: '',
      cronExpression: '',
      params: '',
      remark: ''
    }
  }
}

function handleCloseDialog() {
  dialog.value.visible = false
  dialog.value.title = '添加定时任务'
  formData.value = {
    id: '',
    beanName: '',
    cronExpression: '',
    params: '',
    remark: ''
  }
}

async function submitForm() {
  addFormRef.value.validate(async (isValid) => {
    if (isValid) {
      const id = formData.value.id
      if (id) {
        let updateRes = await request({
          url: `${BASE_URL}/update`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('修改成功')
        handleCloseDialog()
        await handleQuery()
      } else {
        let addRes = await request({
          url: `${BASE_URL}/save`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('添加成功')
        handleCloseDialog()
        await handleQuery()
      }
    }
  })
}

// ====================================================================================================

function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(() => {
      handleQuery()
    })
  })
}

function handleAction(id, action) {
  ElMessageBox.confirm('确认执行该操作吗？?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/doAction`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id,
        action: action
      }
    }).then(() => {
      handleQuery()
    })
  })
}

function handleResetQuery() {
  queryParams.value = {
    beanName: '',
    status: '0',
    pageNum: 1,
    pageSize: 20
  }
  handleQuery()
}

function handleQuery() {
  console.log(queryParams, 'queryParams')

  loading.value = true
  request({
    url: `${BASE_URL}/query`,
    method: 'get',
    params: {
      ...queryParams.value
    }
  }).then((res) => {
    console.log(res, 'res')

    loading.value = false
    list.value = res.content
    total.value = parseInt(res.totalElements)
  })
}

// ====================================================================================================

onMounted(() => {
  handleQuery()
})
</script>
